package com.sctvcloud.longchang.ui.activities;

import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.ArrayMap;
import android.util.Pair;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;

import com.gridsum.tracker.GridsumWebDissector;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.widget.CustomFontEditText;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.longchang.R;
import com.sctvcloud.longchang.application.Constances;
import com.sctvcloud.longchang.base.BaseActivity;
import com.sctvcloud.longchang.beans.ConvenientTelTypeBean;
import com.sctvcloud.longchang.beans.TelInfo;
import com.sctvcloud.longchang.beans.TelInitialsBean;
import com.sctvcloud.longchang.beans.TelTitle;
import com.sctvcloud.longchang.beans.TelephoneListVo;
import com.sctvcloud.longchang.beans.TelephoneTypeVo;
import com.sctvcloud.longchang.http.AbsNetCallBack;
import com.sctvcloud.longchang.http.NetUtils;
import com.sctvcloud.longchang.ui.adapter.ConvenientTelAdapter;
import com.sctvcloud.longchang.ui.adapter.TelephoneListAdapter;
import com.sctvcloud.longchang.ui.adapter.holder.LetterIndexHolder;
import com.sctvcloud.longchang.ui.adapter.holder.TelephoneHolder;
import com.sctvcloud.longchang.ui.adapter.holder.VideoPlayHolder;
import com.sctvcloud.longchang.ui.util.IListShowData;
import com.sctvcloud.longchang.ui.util.RBaseItemDecoration;
import com.sctvcloud.longchang.ui.utils.TitleUtils;
import com.sctvcloud.longchang.utils.MyTextUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 电话页面（可搜索，显示首字母等）
 */
public class TelephoneListActivity extends BaseActivity implements TelephoneHolder.OnTelephoneClickListener, LetterIndexHolder.OnLetterClickLister {
    @BindView(R.id.search_key_ct)
    protected CustomFontEditText searchCt;
    @BindView(R.id.search_clean)
    protected LinearLayout searchCleanLayout;
    @BindView(R.id.tel_list)
    protected RecyclerView telList;
    @BindView(R.id.tel_initials_list)
    protected RecyclerView telInitialsList;
    @BindView(R.id.no_data_txt)
    protected CustomFontTextView noDataTxt;

    public static final String TEL_TYPE_ID = "tel_type_id";
    private String telTypeId;

    private TelephoneListAdapter telephoneAdapter;
    private TelephoneListAdapter letterIndexAdapter;
    private List<IListShowData> showTelList = new ArrayList<>();
    private List<TelInfo> telDataList = new ArrayList<>();
    private List<TelInfo> searchTelDataList = new ArrayList<>();
    private List<IListShowData> telInitialsBeanList = new ArrayList<>();

    //目标项是否在最后一个可见项之后
    private boolean mShouldScroll;
    //记录目标项位置
    private int mToPosition;

    //    private int loadMoreType = 0;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        telTypeId = getIntent().getStringExtra(TEL_TYPE_ID);
        telList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        telList.addItemDecoration(new RBaseItemDecoration(0));
        telList.setItemAnimator(new DefaultItemAnimator());
        telInitialsList.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        telInitialsList.setItemAnimator(new DefaultItemAnimator());
        telInitialsList.addItemDecoration(new RBaseItemDecoration(0));
        searchCleanLayout.setVisibility(View.GONE);
        searchCt.addTextChangedListener(watcher);
        telephoneAdapter = new TelephoneListAdapter(this, null);
        telephoneAdapter.setOnTelephoneClickListener(this);
        telList.setAdapter(telephoneAdapter);

        letterIndexAdapter = new TelephoneListAdapter(this, null);
        telInitialsList.setAdapter(letterIndexAdapter);
        letterIndexAdapter.setOnLetterClickListener(this);
        telList.addOnScrollListener(new RecyclerView.OnScrollListener() {

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
//                if (mShouldScroll && RecyclerView.SCROLL_STATE_IDLE == newState) {
//                    mShouldScroll = false;
//                    smoothMoveToPosition(recyclerView, mToPosition);
//                }

            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                int topPosition = layoutManager.findFirstVisibleItemPosition();
                if (ListUtils.isListValued(showTelList) && showTelList.size() > topPosition) {
                    IListShowData il = showTelList.get(topPosition);
                    if (il instanceof TelTitle) {
                        TelTitle telTitle = (TelTitle) il;
                        refreshLetterIndex(telTitle.getLetter());
                    } else if (il instanceof TelInfo) {
                        TelInfo telInfo = (TelInfo) il;
                        String t1 = MyTextUtils.getSpells(telInfo.getName());
                        refreshLetterIndex(t1);
                    }
                }
            }

        });
        getTelData("");
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_tel_list);
        ButterKnife.bind(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    private void getTelData(String key) {
        telDataList.clear();
        showProgress("正在加载...");
        Map<String, Object> param = new ArrayMap<>();
        param.put("institutionId", telTypeId);
        param.put("keyword", key);
        NetUtils.getNetAdapter().getConveniencePhoneList(getOwnerName(), param, new AbsNetCallBack<TelephoneListVo>(TelephoneListVo.class) {
            @Override
            public void onSuc(TelephoneListVo telVo) {
                if (null != telVo && ListUtils.isListValued(telVo.getConPhoneNoList())) {
                    telDataList.addAll(telVo.getConPhoneNoList());
                }

            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                super.onError(ex, errorMsg);
                toast("数据异常");
            }

            @Override
            public void onEnd() {
                super.onEnd();
                closeProgress();
                initTelData();
            }
        });


    }

    /**
     * 加载初始电话数据
     */
    private void initTelData() {
        TelTitle title;
        TelInitialsBean telInitials;
        showTelList.clear();
        telInitialsBeanList.clear();
        for (int i = 0; i < telDataList.size(); i++) {
            if (i == 0) {
                String t = MyTextUtils.getSpells(telDataList.get(i).getName());
                title = new TelTitle();
                title.setLetter(t);
                title.setViewType(TelephoneListAdapter.VIEWTYPE_LETTER);
                showTelList.add(title);
                showTelList.add(telDataList.get(i));
                telInitials = new TelInitialsBean();
                telInitials.setLetter(t);
                telInitials.setPosition(showTelList.size() - 2);
                telInitials.setViewType(TelephoneListAdapter.VIEWTYPE_LETTER_INDEX);
                telInitialsBeanList.add(telInitials);
            } else {
                String t1 = MyTextUtils.getSpells(telDataList.get(i - 1).getName());
                String t2 = MyTextUtils.getSpells(telDataList.get(i).getName());
                if (!t1.equalsIgnoreCase(t2)) {
                    title = new TelTitle();
                    title.setLetter(t2);
                    title.setViewType(TelephoneListAdapter.VIEWTYPE_LETTER);
                    showTelList.add(title);
                    telInitials = new TelInitialsBean();
                    telInitials.setLetter(t2);
                    telInitials.setPosition(showTelList.size() - 1);
                    telInitials.setViewType(TelephoneListAdapter.VIEWTYPE_LETTER_INDEX);
                    telInitialsBeanList.add(telInitials);
                }
                showTelList.add(telDataList.get(i));
            }

        }
        //TODO 加载初始电话列表 和首字母列表
        initShowListData();
    }

//    /**
//     * 加载搜索筛选过的电话数据
//     */
//    private void initSearchTelData(String key) {
//        TelTitle title;
//        TelInitialsBean telInitials;
//        showTelList.clear();
//        searchTelDataList.clear();
//        telInitialsBeanList.clear();
//        for (int i = 0; i < telDataList.size(); i++) {
//            if (!TextUtils.isEmpty(telDataList.get(i).getName()) && telDataList.get(i).getName().contains(key)) {
//                searchTelDataList.add(telDataList.get(i));
//            }
//        }
//        for (int i = 0; i < searchTelDataList.size(); i++) {
//            if (i == 0) {
//                String t = MyTextUtils.getSpells(searchTelDataList.get(i).getName());
//                title = new TelTitle();
//                title.setLetter(t);
//                title.setViewType(TelephoneListAdapter.VIEWTYPE_LETTER);
//                showTelList.add(title);
//                showTelList.add(searchTelDataList.get(i));
//                telInitials = new TelInitialsBean();
//                telInitials.setLetter(t);
//                telInitials.setPosition(showTelList.size() - 2);
//                telInitials.setViewType(TelephoneListAdapter.VIEWTYPE_LETTER_INDEX);
//                telInitialsBeanList.add(telInitials);
//            } else {
//                String t1 = MyTextUtils.getSpells(searchTelDataList.get(i - 1).getName());
//                String t2 = MyTextUtils.getSpells(searchTelDataList.get(i).getName());
//                if (!t1.equalsIgnoreCase(t2)) {
//                    title = new TelTitle();
//                    title.setLetter(t2);
//                    title.setViewType(TelephoneListAdapter.VIEWTYPE_LETTER);
//                    showTelList.add(title);
//                    telInitials = new TelInitialsBean();
//                    telInitials.setLetter(t2);
//                    telInitials.setPosition(showTelList.size() - 1);
//                    telInitials.setViewType(TelephoneListAdapter.VIEWTYPE_LETTER_INDEX);
//                    telInitialsBeanList.add(telInitials);
//                }
//                showTelList.add(searchTelDataList.get(i));
//            }
//        }
//
//        //TODO 加载搜索电话列表 和首字母列表
//        initShowListData();
//    }

    /**
     * 加载列表数据
     */
    private void initShowListData() {
        if (ListUtils.isListValued(telInitialsBeanList)) {
            for (int i = 0; i < telInitialsBeanList.size(); i++) {
                TelInitialsBean telInitialsBean = (TelInitialsBean) telInitialsBeanList.get(i);
                if (i == 0) {
                    telInitialsBean.setSelected(true);
                } else {
                    telInitialsBean.setSelected(false);
                }
            }
        }
        telephoneAdapter.setData(showTelList);
        letterIndexAdapter.setData(telInitialsBeanList);
        if (!ListUtils.isListValued(showTelList)) {
            noDataTxt.setVisibility(View.VISIBLE);
            telList.setVisibility(View.GONE);
            telInitialsList.setVisibility(View.GONE);
        } else {
            noDataTxt.setVisibility(View.GONE);
            telList.setVisibility(View.VISIBLE);
            telInitialsList.setVisibility(View.VISIBLE);
        }
    }

    private void refreshLetterIndex(String letter) {
        if (ListUtils.isListValued(telInitialsBeanList)) {
            for (int i = 0; i < telInitialsBeanList.size(); i++) {
                TelInitialsBean telInitialsBean = (TelInitialsBean) telInitialsBeanList.get(i);
                if (telInitialsBean.getLetter().equalsIgnoreCase(letter)) {
                    telInitialsBean.setSelected(true);
                } else {
                    telInitialsBean.setSelected(false);
                }
            }
            letterIndexAdapter.setData(telInitialsBeanList);
        }
    }

    @Override
    public void OnLetterClick(TelInitialsBean letter) {
        refreshLetterIndex(letter.getLetter());
        telList.scrollToPosition(letter.getPosition());
        LinearLayoutManager mLayoutManager = (LinearLayoutManager) telList.getLayoutManager();
        mLayoutManager.scrollToPositionWithOffset(letter.getPosition(), 0);
    }

    @Override
    public void OnTelephoneClick(TelInfo info) {
        if (null != info && !TextUtils.isEmpty(info.getPhoneNo())) {
            Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + info.getPhoneNo()));
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                toast(R.string.failed_to_phone);
            }
        } else {
            toast("电话号码为空");
        }
    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER && event.getAction() == KeyEvent.ACTION_DOWN) {
            String key = searchCt.getText().toString().trim();
            if (TextUtils.isEmpty(key)) {
                toast("搜索关键词不能为空");
                return false;
            }

            ArrayList<Pair<String, String>> pairs = new ArrayList<>();
            pairs.add(new Pair<>("行为类型", "主动搜索"));
            GridsumWebDissector.getInstance().trackEvent(TelephoneListActivity.this, "", "搜索", "", 200, pairs);
            getTelData(key);
        }
        return super.dispatchKeyEvent(event);
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String key = searchCt.getText().toString().trim();
            if (!TextUtils.isEmpty(key)) {
                searchCleanLayout.setVisibility(View.VISIBLE);
            }
        }
    };

    @OnClick({R.id.search_clean, R.id.search_cancel})
    protected void OnClick(View v) {
        if (v.getId() == R.id.search_clean) {
            searchCt.setText("");
            searchCleanLayout.setVisibility(View.GONE);
            getTelData("");
        } else if (v.getId() == R.id.search_cancel) {
            finish();
        }

    }

    /**
     * 滑动到指定位置
     */
    private void smoothMoveToPosition(RecyclerView mRecyclerView, final int position) {
        JLog.e("OnItemClick---", "smoothMoveToPosition  position = " + position);
        // 第一个可见位置
        int firstItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(0));
        // 最后一个可见位置
        int lastItem = mRecyclerView.getChildLayoutPosition(mRecyclerView.getChildAt(mRecyclerView.getChildCount() - 1));
        if (position < firstItem) {
            // 第一种可能:跳转位置在第一个可见位置之前
            mRecyclerView.smoothScrollToPosition(position);
        } else if (position <= lastItem) {
            // 第二种可能:跳转位置在第一个可见位置之后
            int movePosition = position - firstItem;
            if (movePosition >= 0 && movePosition < mRecyclerView.getChildCount()) {
                int top = mRecyclerView.getChildAt(movePosition).getTop();
                mRecyclerView.smoothScrollBy(0, top);
            }
        } else {
            // 第三种可能:跳转位置在最后可见项之后
            mRecyclerView.smoothScrollToPosition(position);
            mToPosition = position;
            mShouldScroll = true;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

}
